const day7ttl = 7 * 24 * 60 * 60;

function Login(payload, type) {
    console.log("all----------------", payload, type);
    if (type == "admin") {
        return LoginByAdmin(payload);
    } else {
        return LoginByUser(payload);
    }
}

/**
 * 登录处理
 * @param {*} payload
 * @returns
 */
function LoginByAdmin(payload) {
    console.log("start to login with admin ~~~");
    console.log(payload)
    // 验证验证码
    var captcha = Process(
        "xiang.helper.CaptchaValidate",
        payload.captcha.id,
        payload.captcha.code
    );

    if (captcha !== true) {
        throw new Exception("验证码不正确!", 400);
    }
    var account = payload.mobile;
    if (!account) {
        account = payload.email;
    }
    var user = Process("models.admin.user.get", {
        wheres: [
            { column: "mobile", value: account },
            { column: "status", value: "启用" },
            {
                method: "orwhere",
                column: "email",
                value: account,
            },
        ],
        limit: 1,
    });
    if (!user || !user.length) {
        throw new Exception("用户不存在", 400);
    }
    // 验证密码
    // var password_validate = Process(
    //   "xiang.helper.PasswordValidate",
    //   payload.password,
    //   user[0].password
    // );
    // if (password_validate !== true) {
    //  throw new Exception("密码不正确!", 400);
    // }

    // 增加token等信息
    let ttl = 7 * 24 * 60 * 60

    const sid = payload.sid;
    var jwt = Process(
        "xiang.helper.JWTMake",
        user[0].id,
        { user_name: user[0].name },
        {
            timeout: ttl,
            sid: sid,
        }
    );
    // Process("session.set", "user", user[0], 7 * 24 * 60 * 60);
    // Process("session.set", "token", jwt.token, 7 * 24 * 60 * 60);
    // Process("session.set", "user_id", user[0].id, 7 * 24 * 60 * 60);
    Process("session.SetMany", { "user_id": user[0].id, "user": user[0] }, ttl, sid);

    delete user[0].password;
    // const user_id = Process("session.Get", "user_id");

    return {
        sid: sid,
        user: user[0],
        menus: Process("flows.menu"),
        token: jwt.token,
        expires_at: jwt.expires_at,
    };
}

function isValidMobileNumber(input) {
    // 定义手机号的正则表达式
    const mobileRegex = /^1[3-9]\d{9}$/;

    // 检查输入是否符合手机号格式
    if (input && mobileRegex.test(input)) {
        return true;
    } else {
        return false;
    }
}

function getDateString(year, month, day) {
    // 补全两位数
    const yearStr = year.toString().padStart(4, '0');
    const monthStr = (month + 1).toString().padStart(2, '0');
    const dayStr = day.toString().padStart(2, '0');

    return `${yearStr}${monthStr}${dayStr}`;
}


function ReqSMSCode(phone) {
    log.Trace("phone:%v", phone);
    if (!isValidMobileNumber(phone)) {
        throw new Exception(phone + "请输入有效的手机号码!", 400);
    }
    // save into session
    // phone: 18229950130 
    // phone_cnt: send sms count in a day. default value 6
    const date = new Date(); // 2024年6月9日
    const dateString = getDateString(date.getFullYear(), date.getMonth(), date.getDate());
    console.log(dateString); // 输出: 20240609
    let phone_cnt = phone + "_" + dateString + "_cnt"

    let cnt = Process("session.Get", phone_cnt)
    console.log("phone_cnt", phone_cnt, cnt);
    console.log("---------------------------");

    if (cnt == null) {
        cnt = 0;
        // Process("session.set", phone_cnt, cnt, 24 * 60 * 60);
    }
    console.log("已发送次数为cnt为", cnt);
    log.Info("%v send sms %v time(s)!", phone, cnt);

    if (cnt + 1 > 11) {
        throw new Exception(phone + "已超过当天发次的次数[" + cnt + "]，请明天再试!", 400);
    }


    // 生成随机4位验证码
    const smscode = Math.floor(1000 + Math.random() * 9000);
    Process("plugins.noti.sms", phone, smscode + ",1");
    console.log("smscode phone ----> ", phone, smscode);
    Process("session.set", phone, smscode, 60 * 5);
    Process("session.set", phone_cnt, cnt + 1, 24 * 60 * 60);
    // invoke api to sent out sms code to phone
    // 18229950130: $sms_code
    // redis {18229950130: $sms_code , phone_cnt: 1 }
    return { smscode: "12" + smscode - 3 };
}

function LoginByUser(payload) {
    console.log("start to login with user ~~~");
    console.log(payload)
    // 验证验证码
    let smscode = payload.smscode
    //TODO compare smscode with value in redis
    var account = payload.mobile;

    let sessionSmscode = Process("session.Get", account);
    // console.log("sessionSmscode", sessionSmscode);
    let flag = smscode == sessionSmscode;
    if (!flag) {
        throw new Exception("验证码不正确!", 400);
    }
    console.log("account------------>", account);
    if (!account) {
        throw new Exception("请提供手机号码!", 400);
    }
    var user = Process("models.admin.user.get", {
        wheres: [
            { column: "mobile", op: "eq", value: account },
            //  { column: "status", value: "启用" },
        ],
        limit: 1,
    });
    // console.log("user=111111==>", user);
    if (!user || !user.length) {
        console.log(account, "用户不存在");
        // throw new Exception("用户不存在", 400);
        let res = Process("models.admin.user.Save", { "name": "n" + account, "mobile": account, "email": account + "@ys.com" });
        console.log("创建用户[" + res + "]成功!")
        user = Process("models.admin.user.get", {
            wheres: [
                { column: "mobile", op: "eq", value: account },
                //  { column: "status", value: "启用" },
            ],
            limit: 1,
        });
        console.log("新用户信息:", user);
    }
    // 验证密码
    // var password_validate = Process(
    //   "xiang.helper.PasswordValidate",
    //   payload.password,
    //   user[0].password
    // );
    // if (password_validate !== true) {
    //  throw new Exception("密码不正确!", 400);
    // }

    // 增加token等信息
    const sid = Process("utils.str.uuid"); // payload.sid;
    var jwt = Process(
        "utils.jwt.Make",
        user[0].id,
        { user_name: user[0].name },
        {
            timeout: day7ttl,
            sid,
        }
    );

    // Process("session.set", "user", user[0], 7 * 24 * 60 * 60);
    // Process("session.set", "token", jwt.token, 7 * 24 * 60 * 60);
    // Process("session.set", "user_id", user[0].id, 7 * 24 * 60 * 60);
    // Set Session
    // 在登录时只有这驼

    Process("session.SetMany", { "user_id": user[0].id, "user": user[0] }, day7ttl, sid);

    delete user[0].password;

    return {
        sid: sid,
        user: user[0],
        //  menus: Process("flows.menu"),
        token: jwt.token,
        expires_at: jwt.expires_at,
    };
}

function Logout() {
    console.log("--------- logout ----------------");

    return { code: 200, message: "success" };
}
// yao run models.admin.user.Save '::{"email":"test@qq.com","mobile":"18229950131","password":"Hhz!@123","password2nd":"Hhz!@123","name":"n18229950131"}'
// yao run models.admin.user.Save '::{"email":"18229950133@ys.com","mobile":"18229950133","name":"n18229950133"}'